package common.jdbc.sql.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import common.jdbc.sql.DBType;
import common.jdbc.sql.SqlAdapter;

/**
 * @作者： caopengfei
 * @时间： 2020/9/7
 */
public class SqlServerAdaper extends SqlAdapter {

    @Override
    public String getDriverClass() {
        return "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    }

    @Override
    public String getTestSql() {
        return "SELECT 1 ";
    }

    @Override
    public String getUrl(String ip, String port, String dbName) {
        //eidt by dangbo 根据端口号是否填写修改返回url格式，指定数据库实例不需要端口号
        if(StringUtils.isNotEmpty(port)){
            return "jdbc:sqlserver://"+ip+":"+port+";databaseName="+dbName+";loginTimeout=3;";
        }
        return "jdbc:sqlserver://"+ip+";databaseName="+dbName+";loginTimeout=3;";
    }

    @Override
    public String getDate(String date) {
        return "'"+date+"'";
    }

    @Override
    public String getLength(String zdm, String zdcd) {
        if(zdcd.indexOf(",")>-1) {
            int zccd = Integer.parseInt(zdcd.substring(0,zdcd.indexOf(",")));//逗号左侧数字
            int xscd = Integer.parseInt(zdcd.substring(zdcd.indexOf(",")+1));//小数部分长度
            int zscd = zccd - xscd;
            if (zdm.indexOf(".") > -1) {
                return " ( LEN(SUBSTRING(" + zdm + ",0,charindex('.'," + zdm + "))) <= "+ zscd
                        + " AND LEN (SUBSTRING("+zdm+",charindex('.',"+zdm+")+1,LEN("+zdm+"))) <= "+ xscd
                        + " ) ";
            }else{
                return "LEN(ISNULL("+zdm+",'')) <= " + (zccd+1);
            }
        }
        return "LEN(ISNULL("+zdm+",'')) <= " + Integer.parseInt(zdcd);
    }

    @Override
    public String getNotLength(String zdm, String zdcd) {
        if(zdcd.indexOf(",")>-1) {
            int zccd = Integer.parseInt(zdcd.substring(0,zdcd.indexOf(",")));//逗号左侧数字
            int xscd = Integer.parseInt(zdcd.substring(zdcd.indexOf(",")+1));//小数部分长度
            int zscd = zccd - xscd;
            if (zdm.indexOf(".") > -1) {
                return " ( LEN(SUBSTRING(" + zdm + ",0,charindex('.'," + zdm + "))) > "+ zscd
                        + " OR LEN (SUBSTRING("+zdm+",charindex('.',"+zdm+")+1,LEN("+zdm+"))) > "+ xscd
                        + " ) ";
            }else{
                return "LEN(ISNULL("+zdm+",'')) > " + (zccd+1);
            }
        }
        return "LEN(ISNULL("+zdm+",'')) > " + Integer.parseInt(zdcd);
    }

    @Override
    public String getDbtype() {
        return DBType.SQLSERVER.dbName();
    }

}
